package com.dahua.messagesyncsh.common.aop;

import com.dahua.messagesyncsh.common.Constants;
import com.dahua.messagesyncsh.common.annotation.Permission;
import com.dahua.messagesyncsh.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Slf4j
@Aspect
@Component
public class PermissionAop {

    @Value("${permission.ip}")
    private String ip;

    private final List<String> PERMISSION_IP = Collections.singletonList("106.15.93.216");

    @Pointcut("@annotation(com.dahua.messagesyncsh.common.annotation.Permission)")
    public void pointcut() {
    }

    @Before(value = "pointcut()")
    public void before(JoinPoint point) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            String intoIP = HttpUtil.getIp(request);

            if (!PERMISSION_IP.contains(intoIP)) {
                throw new RuntimeException("IP地址不在白名单中");
            }
        } catch (Exception e) {
            log.error("【PermissionAop】: {}", e.getMessage());
        }

    }
}
